<template>
	
			
	<view>
  <view class="draw">
   <canvas
				class="canvas"
				disable-scroll 
				type="2d" 
				id="myCanvas"
				@touchstart="handleTouchstart"
				@touchmove="handleTouchmove">
			</canvas>
  </view>
  <view class="flex_center mt-106">
    <view class="reset">重新绘制</view>
    <view class="pay_btn ml-30">🔒解锁答案</view>
  </view>
</view>
			
		
</template>

<script>
	export default {
		data() {
			return {
				top: 0,
				canvas: null,
				title: ''
			}
		},
		onLoad() {
			const menuData = uni.getMenuButtonBoundingClientRect()
			uni.getSystemInfo({
			  success: (res) => {
			    let navPadding = menuData.top - res.statusBarHeight
			    // 顶部高度 = 状态栏高度 + 胶囊按钮行高度 + 胶囊按钮上下的padding
			    let navHeight = res.statusBarHeight + navPadding * 2 + menuData.height
			    // 设置canvas的物理宽高
			    this.canvasWidth = res.windowWidth - 100
				this.canvasHeight = res.windowHeight - navHeight - 20
				this.top = navHeight
			  }
			})
		},
		onReady() {
			this.$nextTick(() => {
				this.initCanvas()
			})
		},
		methods: {
			initCanvas() {
			const query = uni.createSelectorQuery().in(this)
				query.select('#myCanvas')
					.fields({ node: true, size: true })
					.exec(async (res) => {
						// 修改canvas的逻辑宽高
						let canvasw = Math.ceil(res.width)
						let canvash = Math.ceil(res.height)
						// 如果不修改canvas的逻辑宽高，仅通过样式修改canvas的宽高，会导致绘图时比例不对，
						// 如将物理宽度改为600，但逻辑宽度还是300，假设画图时的起点x是100，那么实际看到的绘图起点是200
						const canvas = res[0].node
						this.canvas = canvas
						this.ctx = canvas.getContext('2d')
						// canvas.width = this.canvasWidth
						// canvas.height = this.canvasHeight
						// 注意：按照上面方式调整，虽然逻辑宽高和物理宽高保持一致了，但是会发现画出来的线会有锯齿不够清晰
						// 因为不同设备上物理像素与逻辑像素是不一致的
						// 因此canvas的逻辑宽高等于物理宽高分别*dpr
						const dpr = wx.getSystemInfoSync().pixelRatio
						canvas.width = canvasw * dpr
						canvas.height = canvash * dpr
						// 假设dpr等于2，,那么canvas的物理宽度是600，逻辑宽度就是1200，
						// 假设画图时的起点x是100，那么实际看到的绘图起点是50，此时只需要将绘图内容进行等比例放大即可
						this.ctx.scale(dpr, dpr)
						// const { img } = await this.loadImg('http://content.daylucky.cn/admin/image/m64ff4by7wjss1xb37g6pt5t.png')
						// console.log(img, 'img')
						// this.ctx.drawImage(img, 0, 0, canvasw, canvash)
						// this.ctx.restore()
					})
			},
			/*
			*	预加载图片
			*/
			loadImg(url) {
				const {
					canvas
				} = this
				return new Promise((resolve, reject) => {
					const img = canvas.createImage()
					img.src = url
					img.onload = (e) => {
						resolve({
							code: 200,
							img,
						})
					}
					img.onerror = () => {
						reject(` img error`)
					}
				})
			},
			handleTouchstart(e) {
				this.lineBegin(e.touches[0].x, e.touches[0].y)
			},
			handleTouchmove(e) {
				this.lineTo(e.touches[0].x, e.touches[0].y)
			},
			lineBegin(x, y) {
				this.ctx.beginPath()
				// 新版Canvas 2D接口，直接修改属性即可
				console.log(123)
				this.ctx.lineCap = 'round'
				this.ctx.lineWidth = 5
				this.startX = x
				this.startY = y
				this.ctx.moveTo(this.startX, this.startY)
			},
			lineTo(x, y) {
				console.log(x, y)
				this.ctx.lineTo(x, y)
				this.ctx.stroke()
				this.ctx.moveTo(x, y)
			},
			clearContext() {
				this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
			},
			confirm() {
				uni.canvasToTempFilePath({
					canvas: this.canvas, 
					success: (res) => {
						this.rotateImage(res.tempFilePath)
					}
				})
			},
			// 横屏签名，但是canvas的方向是垂直的，导出的图片也是竖屏，需要将图片进行旋转
			rotateImage(filePath) {
				uni.createSelectorQuery()
					.select('#myCanvas2')
					.fields({ node: true, size: true })
					.exec((res) => {
						// 首先绘制一个宽高与上面canvas相反的canvas
						const canvas = res[0].node
						this.canvas2 = canvas
						this.ctx2 = canvas.getContext('2d')
						
						const dpr = wx.getSystemInfoSync().pixelRatio
						canvas.width = this.canvasHeight * dpr
						canvas.height = this.canvasWidth * dpr
						this.ctx2.scale(dpr, dpr)
						// 绘制上述导出的签名图片到新的canvas上
						const img = this.canvas2.createImage()
						img.src = filePath
						img.onload = () => {
							// 签名图片旋转绘画解析在下方
							this.ctx2.translate(0, this.canvasWidth);
							this.ctx2.rotate(270 * Math.PI / 180)
							this.ctx2.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight)
							
							uni.canvasToTempFilePath({
								canvas: this.canvas2, 
								success: (res) => {
									this.handleUploadFile(res.tempFilePath)
								}
							}) 
						}						
					})
			},
			handleUploadFile(filePath) {
				uni.uploadFile({
		  			url: config.requestUrl + '/biz/file/upload/annex', 
			        filePath,
	  		        name: 'file',
					header: {
						'Authorization': getToken()
					},
				  	success: (res) => {
						// 调用接口成功
						if(res.statusCode == 200) {
							// 解析服务器返回数据
							const data = JSON.parse(res.data)
							if(data.code == 200) {
								const responseUrl = config.requestUrl + data.filePath
								const eventChannel = this.getOpenerEventChannel()
								eventChannel.emit('getSignImage', {filePath: responseUrl, fileId: data.fileId});
								this.back()
							}
						} else {
							uni.hideLoading()
						}
				  },
				  fail: (res) => {
				    uni.hideLoading()
				  }
				})
			},
			back() {
				uni.navigateBack()
			}
		}
	}
</script>	
<style lang="scss" scoped>
	.draw {
    width: 588rpx;
    height: 770rpx;
    border-radius: 700rpx;
    // background: url(http://content.daylucky.cn/admin/image/m64ff4by7wjss1xb37g6pt5t.png) no-repeat left top/ 100% 100%;
    -webkit-clip-path: ellipse(54% 54% at 50% 50%);
    overflow: hidden;
    clip-path: ellipse(54% 54% at 50% 50%);
    .canvas {
      width: 100%;
      height: 100%;
    }
  }
  .reset {
    width: 256rpx;
    height: 76rpx;
    font-family: DreamHanSerifCN-W4;
    border-radius: 38rpx;
    border: 2rpx solid #000000;
    font-size: 32rpx;
    line-height: 76rpx;
    color: #000000;
    text-align: center;
  }
  .pay_btn {
    width: 256rpx;
    height: 76rpx;
    background: #000000;
    border-radius: 38rpx;
    font-size: 32rpx;
    color: #FFFFFF;
    line-height: 76rpx;
    text-align: center;
    font-style: normal;
  }

	
</style>